import axios from 'axios';

import { getEnv, getEnvInfo } from '@/utils/env';
import { Toast } from 'antd-mobile';
import { history } from 'umi';

const env = getEnv();
const envInfo = getEnvInfo(env);

// 请求前获取token(首次加载并发导致无token)
function getToken() {
  return new Promise((resolve) => {
    const token = localStorage.getItem('token');
    if (token) {
      resolve(token);
    } else {
      let count = 0;
      const st = setInterval(() => {
        const token = localStorage.getItem('token');
        if (token || count >= 6) {
          resolve(token);
          clearInterval(st);
        } else {
          count++;
        }
      }, 100);
    }
  });
}

// 创建axios实例
const service = axios.create({
  withCredentials: true, // 跨域允许携带cookies
  baseURL: env === 'local' ? '' + envInfo.URL : envInfo.URL, // api 的 base_url
  // timeout: 60000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
  if (getToken()) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  config.headers['Content-Type'] = 'application/json'
  return config
},
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      setTimeout(() => {
        Toast.show(response.message);
      }, 100);
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        setTimeout(() => {
          Toast.show('网络请求超时');
        }, 100);
        return Promise.reject(error)
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        setTimeout(() => {
          Toast.show('网络请求错误');
        }, 100);
        return Promise.reject(error)
      }
    }
    if (code === 401) {
      setTimeout(() => {
        Toast.show('登录状态已过期');
      }, 100);
      location.reload() // 为了重新实例化
    } else if (code === 403) {
      history.push({ path: '/401' })
    } else {
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        setTimeout(() => {
          Toast.show(errorMsg);
        }, 3000);
      }
    }
    return Promise.reject(error)
  }
)
export default service

